

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * 外网
 *
 * Created by zhoub on 2019/12/9.
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {
        int port = 8081;

        ServerSocket serverSocket = new ServerSocket(port);
        while(true){
            final Socket socket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("has a client connect");
                    InputStream inputStream = null;
                    try {
                        OutputStream outputStream = socket.getOutputStream();
                        inputStream = socket.getInputStream();
                        boolean flag = true;
                        while(flag){
                            outputStream.write("Hello,I'm Server eof".getBytes("UTF-8"));
                            outputStream.flush();
                            byte[] buf = new byte[1024];
                            int len=0;
                            StringBuilder sb = new StringBuilder();
                            while((len=inputStream.read(buf))!=-1){
                                String receive = new String(buf,0,len,"UTF-8");
                                sb.append(receive);
                                if(receive.endsWith("eof")){
                                    break;
                                }
                            }
                            System.out.println("receive:"+sb.toString());

                            Thread.sleep(5*60*1000);
                        }
                        inputStream.close();
                        outputStream.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
